package com.si.ui;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.swing.GroupLayout;
import javax.swing.JPanel;

public class PreviewCanvas extends JPanel implements IWidget, IImageCanvas {

	private static final long serialVersionUID = -2067241091608611108L;
	
	private final Lock lock;
	private BufferedImage image;
	
	public PreviewCanvas() {
		this.lock = new ReentrantLock();
	}

	@Override
	public void initialize(final Map<String, Component> components) {
		this.buildLayout();
	}

	private void buildLayout() {
		GroupLayout layout = new GroupLayout(this);
		this.setLayout(layout);
		layout.setHorizontalGroup(
				layout.createParallelGroup(GroupLayout.Alignment.LEADING)
		);
		layout.setVerticalGroup(
				layout.createParallelGroup(GroupLayout.Alignment.LEADING)
		);
	}
	
	@Override
	public void paint(final Graphics g) {
		super.paint(g);
		this.lock.lock();
		try {
			if(this.image != null) g.drawImage(this.image, 0, 0, this.image.getWidth(), this.image.getHeight(), null);
		} finally {
			this.lock.unlock();
		}
	}

	@Override
	public void setImage(final BufferedImage image) {
		this.lock.lock();
		try {
			this.image = image;
		} finally {
			this.lock.unlock();
		}
		this.repaint();
	}
}
